package cn.imokay.readwrite;

import org.springframework.http.converter.json.GsonBuilderUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.zip.GZIPOutputStream;

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();


        for (int i = 0; i < 6; i++) {
            String finalI = i+1+"";
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"开始写");
                myCache.put(finalI,finalI);
                System.out.println(Thread.currentThread().getName()+"写完了");
            },"线程"+finalI).start();
        }

        for (int i = 0; i < 6; i++) {
            String finalI = i+1+"";
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"开始读");
                try {
                    System.out.println(Thread.currentThread().getName()+"读到了："+myCache.get(finalI));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            },"线程"+finalI).start();
        }

    }
}

//资源类
class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);

    public void put(String key, Object value) {

        try {
            lock.writeLock().lock();
            TimeUnit.SECONDS.sleep(5);
            map.put(key, value);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //lock.writeLock().unlock();
        }
    }

    public Object get(String key) throws InterruptedException {
        lock.readLock().lock();
        //TimeUnit.SECONDS.sleep(1);
        Object o = map.get(key);
        lock.readLock().unlock();
        return o;
    }
}
